<?php
//include 'function.php';
//include 'DatabaseObject/Video.php';

class UserController extends Zend_Controller_Action
{
  private $db;
  private $user;
  private $user_table;
  private $logger;

  public function init()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    //print $session->user->get("id");
    /* print "<pre>"; */
    /* print_r($session->user); */
    /* print "</pre>"; */
    if(!isset($session->user) || $session->user->get("id") < 1)
      {
	//print "Location<br/>";
	header("Location: /account/login");
	die("you need to login to continue;<br/>");
      }

    $db_obj = new myDb();
    $this->db = $db_obj->getDb();
    /* $this->db->setFetchMode(Zend_Db::FETCH_OBJ); */

    /* $user = new User(); */
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    Zend_Db_Table::setDefaultAdapter($this->db);

    $this->user_table = new Application_Model_DbTable_User();

    try{
      if (!is_file(LOG))
	  touch(LOG);
      $writer = new Zend_Log_Writer_Stream(LOG);
      $this->logger = new Zend_Log($writer);  
      $this->logger->info("create log");
    }
    catch(Zend_Log_Execption $e)
    {
	print $e->getMessage();
    }
  }

  public function indexAction()
  {
    header("Location: /user/user-info");
  }
  /* do nothing but show the execute result in msg.phtml. */
  public function msgAction()
  {
  }

  public function userInfoAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');

    $select = $this->db->select();
    $select->from(array("u"=>"users"), 
		  array("college_name"=>"c.name", "school_name"=>"s.name"))
      ->join(array("c"=>"college"), "c.coid = u.college_id")
      ->join(array("s"=>"school"), "s.scid = u.school_id")
      ->where("u.id = ".$session->user->get("id"));

    $this->view->user = $this->db->fetchRow($select);
  }
  public function profileSuccessAction()
  {
	$this->view->res = true;
	$this->view->msg = "保存成功";
  }
  public function updateProfileAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    if ($this->getRequest()->isPost())
      {
	foreach($_POST as $key => $val)
	  {
	    $session->user->set($key, $val);
	  }
	$usermapper = new Application_Model_UserMapper();
	$usermapper->save($session->user);
	
	$this->view->res = true;
	$this->view->msg = "保存成功";
      }

  }
  public function profileAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');

    /* get the provinces list */
    $sql = 'select provinceID, pname from province';
    $results = $this->db->fetchPairs($sql);
    $this->view->provinces = $results;

    if ($session->user->get("college_id"))
      {
	// get province id of college
	$table = new Application_Model_DbTable_College();
	$where = $this->db->quoteInto('coid = ?', $session->user->get("college_id"));
	$college = $table->fetchRow($where);
	$this->view->college_province = $college['provinceID'];

	// get the college list in the same province
	$table = new Application_Model_DbTable_College();
	$where = $this->db->quoteInto('provinceID = ?', $this->view->college_province);
	$result = $table->fetchAll($where);
	$this->view->colleges = array();
	foreach ($result as $res)
	  {
	    $this->view->colleges[$res['coid']] = $res['name'];
	  }
	// print_r($colleges);

	// get schools in the college
	$table = new Application_Model_DbTable_School();
	$where = $this->db->quoteInto('collegeID = ?', $session->user->get("college_id"));
	$result = $table->fetchAll($where);
	$this->view->schools = array();
	foreach ($result as $res)
	  {
	    $this->view->schools[$res['scid']] = $res['name'];
	  }
      }   
  }
  public function changepasswdAction()
  {
    $passwd = $this->getRequest()->getParam('passwd');
    $new_passwd = $this->getRequest()->getParam('new_passwd');
    if (!isset($passwd) || empty($passwd))
      {
	$this->view->error = '';
	return;
      }

    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    $where = $this->db->quoteInto('id = ? ', $session->user->get("id"));

    $user_table = new Application_Model_DbTable_User();
    $user = $user_table->fetchRow($where);

    if (count($user) == 0)
      {
	$msg = "<span class='red'>用户不存在</span>";
      }
    else if (count($user) == 1)
      {
	if ($user['password'] == md5($passwd))
	  {
	    $user_table->update(array("password"=>md5($new_passwd)), $where);
	    $msg = "<span class='green'>密码修改成功</span>";
	  }
	else
	  {
	    $msg = "<span class='red'>原始密码不正确</span>";
	  }
      }

    $this->view->error = $msg;
  }
  public function converttoflv( $in, $out )
  {

    /* $cmd = "/usr/local/bin/ffmpeg -v 0 -i $in -ar 11025 $out 2>&1"; */
    $cmd = FFMPEG." -v 0 -i $in -ar 11025 $out 2>&1";
    $fh = popen( $cmd, "r" );
    $this->logger->info("-----------------------------");
    while($c = fgets( $fh ) ) 
      {
	$this->logger->info($c);
      }
    pclose( $fh );
    $this->logger->info("-----------------------------");
  }
  public function getthumbnail( $in, $out )
  {
    //unlink( $out );
    // $cmd = "ffmpeg.exe -i $in -pix_fmt rgb24 -vframes 1 -s 300x200 $out 2>&1";
    $cmd = FFMPEG." -i {$in} -an -ss 00:00:03 -an -r 1 -vframes 1 -y {$out} 2>&1";
    /* $cmd = "/usr/local/bin/ffmpeg -i $in -pix_fmt rgb24 -vframes 1 -s 300x200 $out 2>&1"; */
    // print 'cmd: '.$cmd.'<br/>';
    $fh = popen( $cmd, "r" );
    while( fgets( $fh ) ) { }
    pclose( $fh );
  }
  function getExtend($file_name)
  {
    $extend =explode("." , $file_name);
    return end($extend);
  }
  public function coursesAction()
  {
    $content_table = new Application_Model_DbTable_Content();

    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    $this->view->courses = $content_table->fetchAll('uid='.$session->user->get("id"));
  }
  public function orderAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    
  }
  public function addTagToCat($cat_id, $tag)
  {
    /* $tag = urldecode($tag); */
    $cat_tags = new Application_Model_DbTable_Cattags();
    $where = $this->db->quoteInto('cat_id = ?', $cat_id) . " and ".
      $this->db->quoteInto("tag = ?", $tag);
    /* print $where; */
    $res = $cat_tags->fetchRow($where);
    if ($res)
      return $res['id'];
    else
      return $cat_tags->insert(array("id"=>null, "cat_id"=>$cat_id, "tag"=>$tag));
  }
  public function uploadsAction()
  {
    
  }
  public function uploadCourseAction()
  {
    // get categories list
    $catmapper = new Application_Model_CategoryMapper();
    $this->view->parent_categories = $catmapper->getCategoryList(0);   
  }
  public function receiveCourseAction()
  {
    $this->logger->info("action receiveCourse");
    if ($this->getRequest()->isPost())
      {
	$this->logger->info("is post");
	Zend_Session::start();
	$session = new Zend_Session_Namespace('account');
	if (!isset($session->user) || !($session->user->get("id") > 0))
	  {
	    $this->logger->info("not login, redirect to /account/login");
	    header('Location: /account/login');
	    return;
	  }

	$upload = new Zend_File_Transfer_Adapter_Http();
	$upload->setDestination(VIDEO_PATH);
	$upload->addValidator('Extension', false, FORMAT_SUPPORTED); //swf,avi,
	$this->logger->info("set validattor and destination");
	if ($upload->receive())
	  {
	    // upload success
	    //print_r($_FILES);
	    /* $tmp_name = $_FILES['file_upload']['tmp_name'];//$upload->getFileName('file_upload', false); */
	    $file_name = $upload->getFileName('file_upload', false);
	    $size = $upload->getFileSize('file_upload');
	    $format = $this->getExtend($file_name);
	    $md5 = md5($file_name.date("Y-m-d H:i:s"));
	    $this->logger->info("get filename: ".$file_name);
	    $this->logger->info("get format: ".$format);
	    /* $this->logger->info("get tmp name: ".$tmp_name); */
	    $this->logger->info("get md5: ".$md5);

	    /* rename the original filename to md5 filename */
	    $file = $md5.".".$format;
	    $r = rename(VIDEO_PATH.$file_name, VIDEO_PATH.$file);
	    $this->logger->info("rename :" .VIDEO_PATH.$file_name ." to ". VIDEO_PATH.$file);
	    $this->logger->info("result: ".$r);

	    /* convert to flv */
	    if (strpos(FORMAT_NEED_CONVERT, $format))
	      {
		$file1 = $md5.".flv";
		$this->logger->info("need to convert");
		$this->logger->info("convert ".VIDEO_PATH.$file . " to " . VIDEO_PATH.$file1);
	    	$this->converttoflv(VIDEO_PATH.$file, VIDEO_PATH.$file1);
		$file = $file1;
	      }
	    /* else */
	    /*   { */
	    /* 	$r = rename($tmp_name, VIDEO_PATH.$file); */
	    /* 	$this->logger->info("rename ".$tmp_name ." to ". VIDEO_PATH.$file); */
	    /* 	$this->logger->info("result of rename: ".$r); */
	    /*   } */

	    /* get thumbnail */
	    $thumbnail = $md5.'.jpg';
	    $this->getthumbnail(VIDEO_PATH.$file,
	    			THUMBNAILS_PATH.$thumbnail);
	    $this->logger->info("get thumbnail ".THUMBNAILS_PATH.$thumbnail);
	    $duration = Application_Model_ContentMapper::video_duration(VIDEO_PATH.$file);

	    /* insert to content table*/
	    $param = array(//'id' => '1',
			   'title'=>$this->getRequest()->getParam('title'),
			   'descript'=>$this->getRequest()->getParam('descript'),
			   'cat_id'=>Application_Model_CategoryMapper::getLastCatId($_POST),
			   'path'=>$file,
			   'format'=>$format,
			   'size'=>$size,
			   'uid'=>$session->user->get("id"),
			   'ori_price'=>$this->getRequest()->getParam('ori_price'),
			   'dis_price'=>$this->getRequest()->getParam('dis_price'),
			   'promotion'=>$this->getRequest()->getParam('promotion') == 'on' ? 1 : 0,
			   'thumb'=>$thumbnail,
			   'duration'=>$duration['duration'],
			   'seconds'=>$duration['seconds']
	);
	    $content = new Application_Model_Content($param);
	    $cont_mapper = new Application_Model_ContentMapper();
	    $cont_id = $cont_mapper->save($content);

	    // insert tags	    
	    $tags_table = new Application_Model_DbTable_Tags();
	    $where = $this->db->quoteInto('cont_id = ?', $cont_id);
	    $tags_table->delete($where);
	    $tag1 = $this->getRequest()->getParam('tag1');
	    $cat_id = $this->getRequest()->getParam('cat');
	    if (isset($tag1) && !empty($tag1))
	      {
		$tag_id = $this->addTagToCat($cat_id, $tag1);
		$tags_table->insert(array('cont_id'=>$cont_id, 'tag_id'=>$tag_id, 'uid'=>$session->user->get("id")));
	      }
	    $tag2 = $this->getRequest()->getParam('tag2');
	    if (isset($tag2) && !empty($tag2))
	      {
		$tag_id = $this->addTagToCat($cat_id, $tag2);
		$tags_table->insert(array('cont_id'=>$cont_id, 'tag_id'=>$tag_id, 'uid'=>$session->user->get("id")));
	      }
	    $tag3 = $this->getRequest()->getParam('tag3');
	    if (isset($tag3) && !empty($tag3))
	      {
		$tag_id = $this->addTagToCat($cat_id, $tag3);
		$tags_table->insert(array('cont_id'=>$cont_id, 'tag_id'=>$tag_id, 'uid'=>$session->user->get("id")));
	      }

	    $this->view->res = true;
	    $this->view->messages = array('上传成功');
	    //$this->view->messages = array('upload success');
	    /* header('Location: /user/upload-success'); */
	  }
	else
	  {
	    // upload failed
	    $this->view->res = false;
	    $this->view->messages = $upload->getMessages();
	    /* header('Location: /user/upload-success');  */
	  }
      }
    
  }
  public function uploadInfoAction()
  {
	  /*
	     +----------------------------------------------------------------------+
	     | Uploadprogress extension                                             |
	     +----------------------------------------------------------------------+
	     | Copyright (c) 2006-2008 The PHP Group                                |
	     +----------------------------------------------------------------------+
	     | This source file is subject to version 3.01 of the PHP license,      |
	     | that is bundled with this package in the file LICENSE, and is        |
	     | available through the world-wide-web at the following url:           |
	     | http://www.php.net/license/3_01.txt.                                 |
	     | If you did not receive a copy of the PHP license and are unable to   |
	     | obtain it through the world-wide-web, please send a note to          |
	     | license@php.net so we can mail you a copy immediately.               |
	     +----------------------------------------------------------------------+
	     | Author: Christian Stocker (chregu@php.net)                           |
	     +----------------------------------------------------------------------+
	   */

		  if (function_exists("uploadprogress_get_info")) {

				  $info = uploadprogress_get_info($_GET['ID']);
		  } else {
				  $info = false;
		  }

	$this->view->info = $info;
  }

  public function uploadAction()
  {
    // get categories list
    $cat_table = new Application_Model_DbTable_Category();
    $categories = $cat_table->fetchAll();
    //print_r($this->view->categories);
    $this->view->categories = array();
    foreach($categories as $cat)
      {
	$this->view->categories[$cat['id']] = $cat['name'];
      }
    
    // $result = $this->db->query('select id, name from category;');
    // $this->view->categories = $result->fetchAll();

  }
  public function updateCourseAction()
  {
    $cont_id = $this->getRequest()->getParam('id'); 
    $where = $this->db->quoteInto('id = ?', $cont_id);
    $content_table = new Application_Model_DbTable_Content();
    $this->view->course = $content_table->fetchRow($where);
    /* print_r($this->view->course); */

    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    if($this->view->course['uid'] != $session->user->get("id"))
      {
	die('你没有权限进行此操作');
	/* header('Location: /user/courses'); */
	return;
      }

    $cat_id = Application_Model_CategoryMapper::getLastCatId($_POST);
    Application_Model_CategoryMapper::setLastCatId($_POST, $cat_id);
    $_POST['promotion'] = $this->getRequest()->getParam('promotion') == "on" ? 1 : 0;
    $content = new Application_Model_Content($_POST);
    $cont_mapper = new Application_Model_ContentMapper();
    $cont_id = $cont_mapper->save($content);
    // delete the original tags and create new ones.
    $tags_table = new Application_Model_DbTable_Tags();
    $where = $this->db->quoteInto('cont_id = ?', $cont_id);
    $tags_table->delete($where);

    $tag1 = $this->getRequest()->getParam('tag1');
    $cat_id = $this->getRequest()->getParam('cat');
    if (isset($tag1) && !empty($tag1))
      {
	$tag_id = $this->addTagToCat($cat_id, $tag1);
	$tags_table->insert(array('cont_id'=>$cont_id, 'tag_id'=>$tag_id, 'uid'=>$session->user->get("id")));
      }
    $tag2 = $this->getRequest()->getParam('tag2');
    if (isset($tag2) && !empty($tag2))
      {
	$tag_id = $this->addTagToCat($cat_id, $tag2);
	$tags_table->insert(array('cont_id'=>$cont_id, 'tag_id'=>$tag_id, 'uid'=>$session->user->get("id")));
      }
    $tag3 = $this->getRequest()->getParam('tag3');
    if (isset($tag3) && !empty($tag3))
      {
	$tag_id = $this->addTagToCat($cat_id, $tag3);
	$tags_table->insert(array('cont_id'=>$cont_id, 'tag_id'=>$tag_id, 'uid'=>$session->user->get("id")));
      }
    $res = true;
    $msg = "课程保存成功";
    header("Location: /user/msg?res=$res&msg=".urlencode($msg));
    /* header("Location: /user/edit-course-success"); */
  }
  public function editCourseAction()
  {
    // opebn edit page with current info
    $cont_id = $this->getRequest()->getParam('cont_id'); 
    $where = $this->db->quoteInto('id = ?', $cont_id);
    $content_table = new Application_Model_DbTable_Content();
    $course = $content_table->fetchRow($where);
    $this->view->course = $course;

    $mapper = new Application_Model_CategoryMapper();
    $this->view->path = $mapper->categoryPathAction($course->cat_id);

    // get tags on the content
    $select = $this->db->select();
    $select->from(array("t"=>"tags"), array("c.tag", "t.tag_id"))
      ->join(array("c"=>"cat_tags"), "c.id = t.tag_id")
      ->where("t.cont_id = $cont_id");
    $this->view->tags = $this->db->fetchAll($select);

  }
  public function editCourseSuccessAction()
  {
    $this->view->msg = "<span class='green'>保存成功</span>";
  }
  public function deleteCourseAction()
  {
    $cont_id = $this->getRequest()->getParam('cont_id');

    // delete from content table
    $content = new Application_Model_DbTable_Content();
    $where = $this->db->quoteInto('id = ?', $cont_id);
    $del = $content->delete($where);

    if ($del == 1)
      {
	$this->view->errno = 0;
	$this->view->msg = "内容已删除";
      }
    else if($del == 0)
      {
	$this->view->errno = 1;
	$this->view->msg = "没有找到对应的内容";
      }
    else{}
  }
  public function uploadSuccessAction()
  {
    // get the latest upload    
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    $where = $this->db->quoteInto('uid = ?', $session->user->get("id"));

    $table = new Application_Model_DbTable_Content();
    $select = $table->select()
      ->where($where)
      ->order("id desc")
      ->limit(4);
    $this->view->courses = $table->fetchAll($select);
  }
  public function historyAction()
  {

  }
  public function accountAction()
  {

  }
  public function friendsAction()
  {

  }
  public function rechargeAction()
  {
    /* get the recharge history */
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');

    $mapper = new Application_Model_OrdersMapper();
    $orders = $mapper->fetchAll("uid = ".$session->user->get("id"), "id desc");

    /* set pageinator */
    $page = 1;
    if(isset($_GET['page']) && is_numeric($_GET['page'])){
      $page = $_GET['page'];
    }
    $paginator = Zend_Paginator::factory($orders);
    $paginator->setCurrentPageNumber($page)->setItemCountPerPage(NUM_PER_PAGE);
    $this->view->orders = $paginator;
    
  }
  public function doRechargeAction()
  {
    
  }
  
  /* set status to TRANSCATION_REFUND_REQUEST in pay history item ; 
   * param 
   * @ id primary key of pay history table
   */
  public function refundRequestAction()
  {
    if (!isset($_GET["pay_id"]))
      {
	$res = false;
	$msg = "参数不正确。";
	header("Location: /user/msg?res=$res&msg=".urlencode($msg));
	die();
      }
    $pay = new Application_Model_PayHistory();
    $mapper = new Application_Model_PayHistoryMapper();
    $mapper->find($_GET["pay_id"], $pay);

    /* set status to refund request */
    $pay->set("status", Application_Model_PayHistory::$TRANSCATION_REFUND_REQUEST);
    $mapper->save($pay);   

    $res = true;
    $msg = "退款申请已提交，请等待审核。";
    header("Location: /user/msg?res=$res&msg=".urlencode($msg));
  }
  public function payHistoryAction()
  {
    /* get the recharge history */
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');

    /* $mapper = new Application_Model_PayHistoryMapper(); */
    /* $results = $mapper->fetchAll("buyer_id = ".$session->user->get("id"), "id desc"); */
    $select = $this->db->select();
    $select->from(array("p"=>"pay_history"), 
		  array("pay_id"=>"p.id", "c.title", "c.descript", "u.username", "u.email", "p.status", "p.price", "p.time"))
      ->join(array("u"=>"users"), "u.id = p.owner_id")
      ->join(array("c"=>"content"), "c.id = p.cont_id")
      ->where("p.buyer_id = ".$session->user->get("id"))
      ->order("p.id desc");
    /* print $select; */
    $results = $this->db->fetchAll($select);
    /* print_r($this->view->results); */
    /* die(); */

    /* set pageinator */
    $page = 1;
    if(isset($_GET['page']) && is_numeric($_GET['page'])){
      $page = $_GET['page'];
    }
    $paginator = Zend_Paginator::factory($results);
    $paginator->setCurrentPageNumber($page)->setItemCountPerPage(NUM_PER_PAGE);
    $this->view->orders = $paginator;    
  }

};
